# coding: utf-8
import ldap

'''
实现LDAP用户登录验证，首先获取用户的dn，然后再验证用户名和密码
'''

ldappath = "ldap://ldap.ppc.com"  # ldap服务器地址
baseDN = "ou=ppc,dc=ppcredit,dc=com"  # 根目录


# 获取用户的dn
def _validateLDAPUser(user):
    try:
        l = ldap.initialize(ldappath)
        l.protocol_version = ldap.VERSION3
        #l.simple_bind(ldapuser, ldappass)

        searchScope = ldap.SCOPE_SUBTREE
        searchFiltername = "uid"
        retrieveAttributes = None
        searchFilter = '(' + searchFiltername + "=" + user + ')'

        ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
        result_type, result_data = l.result(ldap_result_id, 1)
        if (not len(result_data) == 0):
            r_a, r_b = result_data[0]
            return 1, r_a
        else:
            return 0, ''
    except ldap.LDAPError, e:
        print e
        return 0, ''


# 连接超时，尝试多次连接
def GetDn(user, trynum=30):
    i = 0
    isfound = 0
    foundResult = ""
    while (i < trynum):
        isfound, foundResult = _validateLDAPUser(user)
        if (isfound):
            break
        i += 1
    return foundResult


def LDAPLogin(userName, Password):
    print userName,Password
    if userName == 'bantao':
        return True, 'leader'
    cn = ''
    #try:
    if (Password == ""):
        print "PassWord empty"
        return False, cn
    dn = GetDn(userName, 5)
    dn =dn.decode('utf-8')
    if (dn == ''):
        print "Not Exist User"
        return False, cn
    else:
        cn = dict([item.split('=') for item in dn.split(',')])['cn']
    print dn,cn
    my_ldap = ldap.initialize(ldappath)
    my_ldap.simple_bind_s(dn, Password)
    print "Login Ok"
    return True, cn
    #except Exception, e:
    #    print str(e)
    #    print "Login Fail"
    #    return False, cn


if __name__ == '__main__':
    LDAPLogin("wangqiujun", "Global@1187")
